import Vue from 'vue'
import store from './store'
import App from './App'

import Json from './Json' //测试用数据
import api from './api.js' //接口
import rand from './common/random.js'
import sign from './common/sign.js'
import aes from './common/aes.js';

//引入全局配置
import $mConfig from '@/config/config.js';
import $mFormRule from '@/config/formRule.config.js';
import $mConstDataConfig from '@/config/constData.config.js';
import $mRoutesConfig from '@/config/routes.config.js';
// 引入全局方法
import http from '@/request/http.js'
import $mGraceChecker from '@/common/graceChecker';
import $mHelper from '@/common/helper';
import $mRouter from '@/common/router';
import $mPayment from '@/common/payment';
import $mDate from '@/common/date.js';

//挂载全局自定义方法
Vue.prototype.$mStore = store;

Vue.prototype.$http = http;
Vue.prototype.$mConfig = $mConfig;
Vue.prototype.$mFormRule = $mFormRule;
Vue.prototype.$mConstDataConfig = $mConstDataConfig;
Vue.prototype.$mRoutesConfig = $mRoutesConfig;


Vue.prototype.$mGraceChecker = $mGraceChecker;
Vue.prototype.$mHelper = $mHelper;
Vue.prototype.$mRouter = $mRouter;
Vue.prototype.$mPayment = $mPayment;
Vue.prototype.$mDate = $mDate;

//全局变量
Vue.prototype.sucCode = 1; // 请求正确的code

// 路由导航
$mRouter.beforeEach((navType, to) => {


	if (to.route === undefined)
		throw '路由钩子函数中没有找到to对象，路由信息:' + JSON.stringify(to);
	

	// 过滤需要权限的页面
	if (to.route.requiresAuth) {

		if (store.getters.hasLogin) {
			// 已经登录
			uni[navType]({
				url: $mHelper.objParseUrlAndParam(to.route.path, to.query)
			});
		} else {
			// 登录成功后的重定向地址和参数
			let query = {
				redirectUrl: to.route.path,
				...to.query
			};
			// 没有登录 是否强制登录?
			if (store.state.forcedLogin) {
				uni.redirectTo({
					url: $mHelper.objParseUrlAndParam($mRoutesConfig.login.path, query)
				});
			} else {
				uni.navigateTo({
					url: $mHelper.objParseUrlAndParam($mRoutesConfig.login.path, query)
				});
			}
		}
	} else {
		console.log('跳转url:' + to.route,navType)

		uni[navType]({
			url: $mHelper.objParseUrlAndParam(to.route, to.query)
		});
	}
});


const msg = (title, duration=1500, mask=false, icon='none')=>{
	//统一提示方便全局修改
	if(Boolean(title) === false){
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}
const json = type=>{
	//模拟异步请求数据
	return new Promise(resolve=>{
		setTimeout(()=>{
			resolve(Json[type]);
		}, 300)
	})
}

const baseUrl = 'http://localhost:8080';

const globalData = {
	baseUrl: baseUrl, 
	url: baseUrl+"/api/front",
	memberUrl: baseUrl + "/api/member",
    appId:"",
    appKey:"",
    aesKey:"",
    ivKey:"",
	https: 0,
  }

function extend() {
    var length = arguments.length;
    var target = arguments[0] || {};
    if (typeof target!="object" && typeof target != "function") {
        target = {};
    }
    if (length == 1) {
        target = this;
        i--;
    }
    for (var i = 1; i < length; i++) { 
        var source = arguments[i]; 
        for (var key in source) { 
            // 使用for in会遍历数组所有的可枚举属性，包括原型。
            if (Object.prototype.hasOwnProperty.call(source, key)) { 
                target[key] = source[key]; 
            } 
        } 
    }
    return target; 
}

/**
 * 获取微信用户信息
 */
function wxGetUserInfo(code) {
	return new Promise((resolve, reject)=>{
		uni.getUserInfo({
			provider: 'weixin',
			withCredentials: true,
		    success: (infoRes) => {
				infoRes.code = code;
				resolve(infoRes);
			},
		    fail: (res) => {
				reject(res);
			}
		}) ;
	});
}

/**
 * 获取用户信息
 * @param {Object} username
 */
function getUser(username, sessionKey){
	var getUser_url= globalData.memberUrl+"/user/get";
	var nonce_str=rand.getRand();//获取随机数
	var postParams=[];//签名数组
	postParams[0]=["username",username];
	postParams[1]=["appId",globalData.appId];
	postParams[2]=["nonce_str",nonce_str];
	postParams[3]=["https",globalData.https];
	postParams[4]=["sessionKey", sessionKey];
	var signVal=sign.createSign(postParams, globalData.appKey);//签名
	//获取信息
	return new Promise((resolve, reject)=>{
		uni.request({
			url: getUser_url,
			data: {
				username: username,
				appId: globalData.appId,
				nonce_str: nonce_str,
				https: globalData.https,
				sign: signVal,
				sessionKey: sessionKey,
			},
			method: 'GET',
			success: (res) =>{
				if(res.data.code == 201){
					resolve(res.data.body);
				}else{
					reject(res.data.message);
				}
			},
			fail: (res)=>{
				reject(res);
			}
		})
	});
}

/**
 * 微信登录
 */
function wxLogin(){
	return new Promise((resolve, reject)=>{
		uni.login({
			provider: 'weixin',
			success: (loginRes) => {
				resolve(loginRes);
			},
			fail: (res)=>{
				reject(res);
			}
		});
	});
}

function weixinLogin(){
	return wxLogin().then((res)=>{
		return wxGetUserInfo(res.code);
	}).then((res)=>{
		return doLogin(res.userInfo, res.code);
	});
}

/**
 * 管理员操作
 * @param {Object} url
 * @param {Object} param
 */
function adminGet(url, params){
	let sessionKey = uni.getStorageSync('sessionKey');
	var nonce_str = rand.getRand();//随机数
	let postParams = [];
	params['appId'] = globalData.appId;
	params['nonce_str'] = nonce_str;
	params['sessionKey'] = sessionKey;
	for(var i in params){
		postParams.push([i, params[i]]);
	}
	var signVal=sign.createSign(postParams, globalData.appKey);//签名
	params['sign'] = signVal;
	return new Promise((resolve, reject)=>{
		uni.request({
			url:  baseUrl+'/api/admin'+ url,
			data: params,
			method:"GET",
			success: (loginRes)=>{
				if(loginRes.data.code != 200){
					reject(loginRes.data.message);
				}else{
					resolve(loginRes.data);
				}
			},
			fail:(res)=>{
				reject(res);
			}
	});
	});
}

/**
 * web接口登录
 * @param {Object} username
 * @param {Object} password
 */
function webLogin(username, password){
	var nonce_str = rand.getRand();//随机数
	let postParams=[];
	let aesPassword = aes.encrypt(password, globalData.aesKey, globalData.ivKey);
	postParams[0] = ['username', username];
	postParams[1] = ['aesPassword', aesPassword];
	postParams[2]=["appId", globalData.appId];
	postParams[3]=["nonce_str",nonce_str];
	var signVal=sign.createSign(postParams, globalData.appKey);//签名
	return new Promise((resolve, reject)=>{
		uni.request({
			url:  globalData.url+'/user/login.jspx',
			data: {
				username: username,
				aesPassword: aesPassword,
				appId: globalData.appId,
				nonce_str:nonce_str,
				sign:signVal
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			method:"POST",
			success: (loginRes)=>{
				if(loginRes.data.code != 200){
					reject(loginRes.data.message);
				}else{
					uni.setStorageSync('sessionKey', loginRes.data.body);
					resolve(loginRes.data);
				}
			},
			fail:(res)=>{
				reject(res);
			}
	});
	});
}

function logout(){
	return memberGet('/user/logout');
}

function getPage(modelId, channelId){
	switch(modelId){
	}
}

function doLogin(userInfo, code){
	var nickName = userInfo.nickName;
	var avatarUrl = userInfo.avatarUrl;
	var gender = userInfo.gender; //性别 0：未知、1：男、2：女
	var province = userInfo.province;
	var city = userInfo.city;
	var country = userInfo.country?userInfo.country:"";
	var nonce_str = rand.getRand();//随机数
	let postParams = [];
	let shareCode = uni.getStorageSync('shareCode');
	postParams[0]=["js_code", code];
	postParams[1]=["grant_type","authorization_code"];
	postParams[2]=["appId", globalData.appId];
	postParams[3]=["nonce_str",nonce_str];
	postParams[4]=["nickName",nickName];
	postParams[5]=["avatarUrl",avatarUrl];
	postParams[6]=["province",province];
	postParams[7]=["city",city];
	postParams[8]=["country",country];
	postParams[9]=['shareCode', shareCode];
	var signVal=sign.createSign(postParams, globalData.appKey);//签名
	//发起网络请求
	return new Promise((resolve, reject)=>{
		uni.request({
			url:  globalData.url+'/user/weixinLogin.jspx',
			data: {
				js_code: code,
				grant_type:'authorization_code',
				appId: globalData.appId,
				nonce_str:nonce_str,
				nickName:nickName,
				avatarUrl:avatarUrl,
				province:province,
				city:city,
				country:country,
				shareCode: shareCode,
				sign:signVal
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			method:"POST",
			success: (loginRes)=>{
				if(loginRes.data.code=="200"){
					uni.setStorageSync('sessionKey', loginRes.data.body.sessionKey);
					resolve(loginRes.data.body);
				}else{
					reject(loginRes)
				}
			},
			fail:(res)=>{
				reject(res);
			}
		});
	});
}

const request= (url, params={}, headers={}, method='GET')=>{
	var _param = extend(params,{
		siteIds: 1,
		https: 1,
		appId: globalData.appId,
	});
	return new Promise(resolve=>{
		uni.request({
			url: globalData.url+url,
			data: _param,
			header: headers,
			method: method,
			success: (res) => {
				resolve(res);
			}
		})
	})
}

/**
 * 文件上传
 */
const upload = (uploadFile) =>{
	return new Promise((resolve, reject) =>{
		uni.showLoading({title:"上传中"});
		let sessionKey = uni.getStorageSync('sessionKey');
		uni.uploadFile({
			url: globalData.memberUrl +'/upload/o_upload',
			filePath: uploadFile,
			fileType: 'image',
			formData: {
				siteIds: 1,
				appId: globalData.appId,
				sessionKey: sessionKey
			},
			name: 'uploadFile',
			success:  (uploadFileRes) => {
				// 上传成功后返回服务器端保存的路径
				resolve(uploadFileRes);
				uni.hideLoading();
			}
		 })
	})
}

const memberRequest= (url, params={}, headers={}, method='GET')=>{
	return new Promise((resolve, reject)=>{
		let sessionKey = uni.getStorageSync('sessionKey');
		if(!sessionKey){
			uni.showModal({
				title: "提示",
				content: "您还没有登录，请先登录？",
				showCancel: true,
				confirmText: "确定",
				success: function (res) {
					if (res.confirm) {
						uni.navigateTo({  
							url: '/pages/user/login'  
						})
					} else if (res.cancel) {
						uni.switchTab({  
							url: '/pages/index/index'  
						})
					}
				}
			});
			return ;
			//reject('请登录');
		}
		var _param = extend(params,{
			siteIds: 1,
			https: 1,
			appId: globalData.appId,
			sessionKey: sessionKey
		});
		uni.request({
			url: globalData.memberUrl+url,
			data: _param,
			header: headers,
			method: method,
			success: (res) => {
				console.log(res);
				if(res.data.code == 3){//session 超时
					uni.hideLoading();
					uni.showModal({
						title: "提示",
						content: "登录超时，请重新登录",
						showCancel: true,
						confirmText: "确定",
						success: function (res) {
							if (res.confirm) {
								uni.navigateTo({  
									url: '/pages/user/login'  
								})
							} else if (res.cancel) {
								uni.switchTab({  
									url: '/pages/index/index'  
								})
							}
						}
					});
				}else if(res.data.code == 302){
					uni.hideLoading();
					uni.showModal({
						title: "提示",
						content: "您还没有登录，请先登录？",
						showCancel: true,
						confirmText: "确定",
						success: function (res) {
							if (res.confirm) {
								uni.navigateTo({  
									url: '/pages/user/login'  
								})
							} else if (res.cancel) {
								uni.switchTab({  
									url: '/pages/index/index'  
								})
							}
						}
					});
				}else{
					resolve(res);
				}
			}
		})
	})
}

const memberRequestWithoutLogin= (url, params={}, headers={}, method='GET')=>{
	return new Promise((resolve, reject)=>{
		let sessionKey = uni.getStorageSync('sessionKey');
		if(!sessionKey){
			console.log('no key');
			 return ;
		}
		var _param = extend(params,{
			siteIds: 1,
			https: 1,
			appId: globalData.appId,
			sessionKey: sessionKey
		});
		uni.request({
			url: globalData.memberUrl+url,
			data: _param,
			header: headers,
			method: method,
			success: (res) => {
				if(res.data.code == 200 || res.data.code == 201){
					resolve(res);
				}
			}
		})
	})
}

const get = (url, params={}, headers ={}) =>{
	return request(url, params, headers, 'GET');
}

const post = (url, params={}, headers ={}) =>{
	return request(url, params, headers, 'POST');
}

const memberGet = (url, params={}, headers ={}) =>{
	return memberRequest(url, params, headers, 'GET');
}

const memberPost = (url, params={}, headers ={}) =>{
	return memberRequest(url, params, headers, 'POST');
}

const memberGetWithoutLogin = (url, params={}, headers ={}) =>{
	return memberRequestWithoutLogin(url, params, headers, 'GET');
}

const prePage = ()=>{
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}

const bMapToQQMap =(lng, lat) => {
    if (lng == null || lng == '' || lat == null || lat == '')
        return [lng, lat];

    var x_pi = 3.14159265358979324;
    var x = parseFloat(lng) - 0.0065;
    var y = parseFloat(lat) - 0.006;
    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    var lng = (z * Math.cos(theta)).toFixed(7);
    var lat = (z * Math.sin(theta)).toFixed(7);

    return {'lng': parseFloat(lng), 'lat': parseFloat(lat)};

}

Vue.config.productionTip = false
Vue.prototype.$fire = new Vue();
Vue.prototype.$store = store;
Vue.prototype.$api = {bMapToQQMap, msg, json, prePage, request, get, post, api, globalData, getUser, weixinLogin, webLogin, memberGet, memberPost, memberRequest, logout, upload,getPage, memberGetWithoutLogin, adminGet, wxLogin,doLogin};


App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()